﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace NetFtp.Core.Utils
{
    public class StringUtils
    {
        public static String ToHexaString(byte[] bytes)
        {
            if (bytes.Length == 0) 
                return "";
            StringBuilder hexaString = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                hexaString.AppendFormat("{0:x2}", b);
            }
            return hexaString.ToString();
        }

        public static string HashString(string password)
        {
            SHA1CryptoServiceProvider mhash = new SHA1CryptoServiceProvider();
            // Converti la chaîne originale en un tableau de Bytes
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(password);
            // Procède au hashage et retourne un tableau de Bytes
            byte[] bytHash = mhash.ComputeHash(bytValue);
            mhash.Clear();
            // hash en hexa
            return StringUtils.ToHexaString(bytHash);
        }

        /// <summary>
        /// Cut a text into list of line.
        /// </summary>
        /// <param name="lines"></param>
        /// <returns></returns>
        public static string[] ParseLines(string content)
        {
            content = content.Replace("\r", "");
            return content.Split(new char[1] { '\n' }, 
                                                StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// Reads the content from a Stream.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string ReadContent(Stream stream)
        {
            string content = "";
            using (StreamReader reader = new StreamReader(stream))
            {
                string text = reader.ReadToEnd();
                using (StringWriter writer = new StringWriter())
                {
                    writer.Write(text);
                    writer.Flush();
                    content = writer.ToString();
                }
            }
            return content;
        }
    }
}
